import { onMounted, onUnmounted } from 'vue';
import { ETB_URL } from '@/common/constants';

export default function useReaderMessenger(etb, readerFrame, options) {
  const loadEtb = () => {
    if (readerFrame.value) {
      readerFrame.value.contentWindow.postMessage({
        type: 'loadBook',
        data: { path: ETB_URL },
      }, '*');
    }
  };

  const renderPage = (pageNumber) => {
    readerFrame.value.contentWindow.postMessage({
      type: 'renderPage',
      data: { pageNumber },
    }, '*');
  };

  const onEtbLoaded = (_etb) => {
    etb.pages = _etb.pages;
    etb.pageNumber = 1;
  };

  const onPageRendered = (data) => {
    etb.pageNumber = data.pageNumber;
    etb.pageWidgets = data.widgets;
    if (options && typeof options.onPageRendered === 'function') options.onPageRendered();
  };

  const onWidgetOperationReceived = async (data, data_type) => {
    console.log(`onWidgetOperationReceived: [${data_type}] `, data)
  };

  const handleReaderMessage = (e) => {
    const { type, data } = e.data;
    switch(type) {
      case 'reader:ready':
        loadEtb();
        break;
      case 'reader:etbLoaded':
        onEtbLoaded(data);
        break;
      case 'reader:pageRendered':
        onPageRendered(data);
        break;
      case 'reader:interactData':
        onWidgetOperationReceived(data, 'interact');
        break;
      case 'reader:behaviorData':
        onWidgetOperationReceived(data, 'behavior');
        break;
      default:
        break;
    }
  };

  onMounted(() => window.addEventListener('message', handleReaderMessage));
  onUnmounted(()  => window.removeEventListener('message', handleReaderMessage));

  return {
    loadEtb,
    renderPage,
  }
}